﻿using PMS.Services.EntityServices.Customers;
using PMS.Services.Utils;
using PMS.Services.Utils.Events;
using System.Linq;
using System.Security.Claims;

namespace PMS.Plugin.ExternalAuth.DingTalkScan.Infrastructure
{
    /// <summary>
    /// DingTalkScan authentication event consumer (used for saving customer fields on registration)
    /// </summary>
    public partial class DingTalkScanAuthenticationEventHandler : IEventHandler<CustomerAutoRegisteredByExternalMethodEvent>
    {
        #region Fields

        private readonly ICustomerService _customerService;

        #endregion

        #region Ctor

        public DingTalkScanAuthenticationEventHandler(ICustomerService customerService)
        {
            _customerService = customerService;
        }

        #endregion

        #region Methods

        /// <summary>
        /// Handle event
        /// </summary>
        /// <param name="eventMessage">Event message</param>
        public void HandleEvent(CustomerAutoRegisteredByExternalMethodEvent eventMessage)
        {
            if (eventMessage.Customer == null || eventMessage.AuthenticationParameters == null)
                return;

            //handle event only for this authentication method
            if (!eventMessage.AuthenticationParameters.ProviderSystemName.Equals(DingTalkScanAuthenticationDefaults.SystemName))
                return;

            //store some of the customer fields
            var CustomerNickName = eventMessage.AuthenticationParameters.Claims?.FirstOrDefault(claim => claim.Type == ClaimTypes.Name)?.Value;
            if (!string.IsNullOrEmpty(CustomerNickName))
            {
                eventMessage.Customer.NickName = CustomerNickName;
                _customerService.UpdateCustomer(eventMessage.Customer);
            }

        }

        #endregion
    }

}
